package cn.amos.mvc.common.util;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * PROJECT: mvc
 * DESCRIPTION: note
 *
 * @author Daoyuan
 * @date 2019/1/7
 */
public class RetrofitUtil {

    private Map<String, String> header;

    private String baseUrl;

    public RetrofitUtil(String baseUrl) {
        this(baseUrl, null);
    }

    public RetrofitUtil(String baseUrl, Map<String, String> header) {
        this.baseUrl = baseUrl;
        this.header = header;
    }

    public Retrofit initRetrofit() {
        Interceptor interceptor = chain -> {
            Request.Builder builder = chain.request().newBuilder();
            if (header != null && header.size() > 0) {
                header.forEach(builder::addHeader);
            }
            return chain.proceed(builder.build());
        };

        X509TrustManager xtm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };

        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());

        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        HostnameVerifier doNotVerify = (hostname, session) -> true;

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.interceptors().add(interceptor);

        OkHttpClient client = builder
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .sslSocketFactory(Objects.requireNonNull(sslContext != null ? sslContext.getSocketFactory() : null))
                .hostnameVerifier(doNotVerify)
                .build();

        return new Retrofit
                .Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(JacksonConverterFactory.create())
                .client(client)
                .build();
    }

}
